

package com.hazelcast.internal.management.operation;

import com.hazelcast.instance.impl.DefaultNodeExtension;
import com.hazelcast.internal.config.LicenseKey;
import com.hazelcast.internal.dynamicconfig.ClusterWideConfigurationService;
import com.hazelcast.internal.dynamicconfig.ConfigurationService;
import com.hazelcast.internal.management.ManagementDataSerializerHook;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;

import java.io.IOException;

/**
 * Operation to update license at runtime.
 */
public class SetLicenseOperation extends AbstractManagementOperation {

    private String licenseKey;

    public SetLicenseOperation() {
    }

    public SetLicenseOperation(String licenseKey) {
        this.licenseKey = licenseKey;
    }

    @Override
    public void run() throws Exception {
        DefaultNodeExtension nodeExtension = (DefaultNodeExtension) getNodeEngine().getNode().getNodeExtension();
        nodeExtension.setLicenseKey(licenseKey);

        LicenseKey licenseKeyObject = new LicenseKey(licenseKey);
        ConfigurationService configurationService = getNodeEngine().getService(ClusterWideConfigurationService.SERVICE_NAME);
        configurationService.persist(licenseKeyObject);
    }

    @Override
    public int getClassId() {
        return ManagementDataSerializerHook.SET_LICENSE;
    }

    @Override
    protected void readInternal(ObjectDataInput in) throws IOException {
        super.readInternal(in);
        licenseKey = in.readString();
    }

    @Override
    protected void writeInternal(ObjectDataOutput out) throws IOException {
        super.writeInternal(out);
        out.writeString(licenseKey);
    }

}
